package com.wander.demo;

import com.sun.management.OperatingSystemMXBean;

import java.lang.management.ManagementFactory;

public class MemoryDemo {
    public static void main(String[] args) {
        MemoryDemo demo = new MemoryDemo();
        demo.getFreeSystemMemory();
        demo.getJVMMaxMemory();
        demo.mallocMemory();
        demo.getJVMFreeMemory();
        demo.getFreeSystemMemory();
    }

    public void getFreeSystemMemory() {
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        long free = osBean.getFreePhysicalMemorySize()/(1024*1024*1024);
        System.out.println("剩余内存：" + free + "G");
    }

    // 获取JVM最大可用堆内存（单位：MB）
    public void getJVMMaxMemory() {
        long stackMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024*1024);
        System.out.println("JVM最大可用堆内存" + stackMemory + "G");
    }

    public void getJVMFreeMemory() {
        long freeMemory = Runtime.getRuntime().totalMemory()/(1024*1024*1024);
        System.out.println("JVM剩余可以用内存：" + freeMemory + "G");
    }

    //申请占用1G的内存
    public void mallocMemory() {
        // 直接申请1GB字节数组（需要-Xmx2G或更大）
        try {
            byte[] oneGB = new byte[1024 * 1024 * 1024];
            System.out.println("Direct allocation success");
        } catch (OutOfMemoryError e) {
            System.err.println("Direct allocation failed");
        }
    }
}
